package com.kafka.demo.consumer.interceptor;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class KafkaProducerInterceptorTTL {

    public static final String brokerList = "localhost:9090";
    public static final String topic = "my-replicated-topic";
    public static final long EXPIRE_INTERVAL = 10 * 1000;

    public static Properties initConfig() {
        Properties properties = new Properties();
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
        properties.put(ProducerConfig.CLIENT_ID_CONFIG, "producer.client.id.demo");
        return properties;
    }

    public static void main(String[] args) {
        Properties properties = initConfig();
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        // 设置消息的 timestamp，触发 Consumer 端 Interceptor 的 TTL
        ProducerRecord<String, String> record1 = new ProducerRecord<>(
                topic,
                0,
                System.currentTimeMillis() - EXPIRE_INTERVAL,
                null,
                "first-expire-data");

        ProducerRecord<String, String> record2 = new ProducerRecord<>(
                topic,
                0,
                System.currentTimeMillis(),
                null,
                "normal-data");

        ProducerRecord<String, String> record3 = new ProducerRecord<>(
                topic,
                0,
                System.currentTimeMillis() - EXPIRE_INTERVAL,
                null,
                "last-expire-data");



        try {
            producer.send(record1);
            producer.send(record2);
            producer.send(record3);
        } catch (Exception e) {
            e.printStackTrace();
        }

        producer.close();
    }

}
